import React from "react";
import { Button, Form, Input, Space, Table, Modal, Input as AntInput, message, Checkbox } from "antd";
import { PlusOutlined, DeleteOutlined, EditOutlined, InboxOutlined } from "@ant-design/icons";
import { DataSetItem, getDataSetList, createDataSet, updateDataSet, deleteDataSet, getDetectionPointDataSetAllName, batchCreateDataSet } from "../../api/gis";
import { useEffect, useState } from "react";
import { useRef } from "react";
import { formatDataSize } from "../../utils/formatUtils";

interface Props {
  planetId: number;
  inspectionAreaId: number;
  detectionPointId: number;
  reloadFlag?: number;
  onChanged?: () => void;
}

const DataSetPanel: React.FC<Props> = ({ planetId, inspectionAreaId, detectionPointId, reloadFlag = 0, onChanged }) => {
  const [data, setData] = useState<DataSetItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<DataSetItem | null>(null);
  const [dataSetName, setDataSetName] = useState("");
  const [importOpen, setImportOpen] = useState(false);
  const [importLoading, setImportLoading] = useState(false);
  const [allNames, setAllNames] = useState<string[]>([]);
  const [selectedNames, setSelectedNames] = useState<string[]>([]);

  // 表格容器与固定高度
  const tableContainerRef = useRef<HTMLDivElement | null>(null);
  const [tableScrollY, setTableScrollY] = useState<number>(0);

  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      // 参照地名管理的计算方式，保持一致体验
      const pageHeight = window.innerHeight;
      const breadcrumbHeight = 48;
      const tabsHeaderHeight = 46;
      const filterFormHeight = 0;
      const actionButtonsHeight = 56;
      const padding = 242; // 与地名管理一致

      const availableHeight =
        pageHeight - breadcrumbHeight - tabsHeaderHeight - filterFormHeight - actionButtonsHeight - padding;
      const tableHeaderHeight = 39;
      const scrollHeight = Math.max(availableHeight - tableHeaderHeight, 100);

      setTableScrollY(scrollHeight);

      const tableBody = tableContainerRef.current.querySelector(".ant-table-body") as HTMLElement | null;
      if (tableBody) {
        tableBody.style.height = scrollHeight + "px";
        tableBody.style.maxHeight = scrollHeight + "px";
      }
    }
  };

  const fetchList = async () => {
    if (!inspectionAreaId || !detectionPointId) return;
    setLoading(true);
    try {
      const res = await getDataSetList({ planet_id: planetId, inspection_area_id: inspectionAreaId, detection_point_id: detectionPointId });
      if (res.code === 200) {
        setData(res.data.list);
        setTotal(res.data.count);
        setCurrent(res.data.page);
        setPageSize(res.data.page_size);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [planetId, inspectionAreaId, detectionPointId, reloadFlag]);

  useEffect(() => {
    const timer = setTimeout(() => {
      calculateTableScrollHeight();
    }, 100);
    const onResize = () => calculateTableScrollHeight();
    window.addEventListener("resize", onResize);
    return () => {
      clearTimeout(timer);
      window.removeEventListener("resize", onResize);
    };
  }, []);

  const handleCreate = () => {
    setEditing(null);
    setDataSetName("");
    setModalOpen(true);
  };

  const handleEdit = (record: DataSetItem) => {
    setEditing(record);
    setDataSetName(record.data_set_name);
    setModalOpen(true);
  };

  const handleDelete = (record: DataSetItem) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除数据集 "${record.data_set_name}" 吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        const res = await deleteDataSet({ ids: [record.id] });
        if (res.code === 200) {
          message.success("删除成功");
          fetchList();
          onChanged?.();
        } else {
          message.error(res.msg || "删除失败");
        }
      }
    });
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) return;
    Modal.confirm({
      title: "确认批量删除",
      content: `确定要删除选中的 ${selectedRowKeys.length} 个数据集吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        const res = await deleteDataSet({ ids: selectedRowKeys.map(Number) });
        if (res.code === 200) {
          message.success("批量删除成功");
          setSelectedRowKeys([]);
          fetchList();
          onChanged?.();
        } else {
          message.error(res.msg || "批量删除失败");
        }
      }
    });
  };

  const handleSave = async () => {
    if (!dataSetName) {
      message.warning("请输入数据集名称");
      return;
    }
    if (!inspectionAreaId || inspectionAreaId <= 0) {
      message.warning("未获取到有效的巡视区，请在左侧选择后再试");
      return;
    }
    if (!detectionPointId || detectionPointId <= 0) {
      message.warning("未获取到有效的探测点，请在左侧选择后再试");
      return;
    }
    const params = { planet_id: planetId, inspection_area_id: inspectionAreaId, detection_point_id: detectionPointId, data_set_name: dataSetName };
    console.log("[DataSetPanel] 保存数据集 params:", params);
    if (editing) {
      const res = await updateDataSet({ id: editing.id, data_set_name: dataSetName });
      if (res.code === 200) {
        message.success("修改成功");
        setModalOpen(false);
        fetchList();
        onChanged?.();
      } else {
        message.error(res.msg || "修改失败");
      }
    } else {
      const res = await createDataSet(params);
      if (res.code === 200) {
        message.success("创建成功");
        setModalOpen(false);
        fetchList();
        onChanged?.();
      } else {
        message.error(res.msg || "创建失败");
      }
    }
  };
  const columns = [
    { title: "ID", dataIndex: "id", key: "id", width: 80, ellipsis: true },
    { title: "数据集名称", dataIndex: "data_set_name", key: "data_set_name", width: 200, ellipsis: true },
    { title: "文件数量", dataIndex: "file_count", key: "file_count", width: 100, ellipsis: true },
    { title: "文件大小", dataIndex: "file_sizes", key: "file_sizes", width: 120, ellipsis: true, render: (v: number) => (v ? formatDataSize(v) : "-") },
    { title: "创建时间", dataIndex: "create_time", key: "create_time", width: 180, ellipsis: true },
    {
      title: "操作",
      key: "action",
      width: 200,
      fixed: "right" as const,
      align: "center" as const,
      render: (_: any, record: DataSetItem) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>删除</Button>
        </Space>
      ),
    },
  ];

  const openImportModal = async () => {
    setImportOpen(true);
    setSelectedNames([]);
    setImportLoading(true);
    try {
      const res = await getDetectionPointDataSetAllName({ planet_id: planetId });
      if (res.code === 200) {
        setAllNames(res.data?.data_set_names || []);
      } else {
        message.error(res.msg || "获取数据集名称失败");
      }
    } catch (e: any) {
      message.error(e?.message || "获取数据集名称失败");
    } finally {
      setImportLoading(false);
    }
  };

  const handleImport = async () => {
    if (selectedNames.length === 0) {
      message.warning("请至少选择一个数据集名称");
      return;
    }
    try {
      const res = await batchCreateDataSet({
        planet_id: planetId,
        inspection_area_id: inspectionAreaId,
        detection_point_id: detectionPointId,
        data_set_names: selectedNames,
      });
      if (res.code === 200) {
        message.success("批量创建成功");
        setImportOpen(false);
        fetchList();
        onChanged?.();
      } else {
        message.error(res.msg || "批量创建失败");
      }
    } catch (e: any) {
      message.error(e?.message || "批量创建失败");
    }
  };

  return (
    <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
      {/* <div style={{ flexShrink: 0 }}>
        <Form layout="inline" className="filter-form" labelCol={{ style: { width: 120 } }}>
          <Form.Item label="数据集名称" style={{ width: 320 }}>
            <Input placeholder="请输入数据集名称搜索" />
          </Form.Item>
          <Form.Item style={{ paddingLeft: 40 }}>
            <Space>
              <Button type="primary">筛选</Button>
              <Button>清除</Button>
            </Space>
          </Form.Item>
        </Form>
      </div> */}

      <div style={{ marginBottom: 16, marginTop: 16, display: "flex", justifyContent: "space-between", alignItems: "center", flexShrink: 0 }}>
        <div>
          <Button type="primary" danger onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0}>
            批量删除
          </Button>
        </div>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新建数据集
          </Button>
          <Button icon={<InboxOutlined />} onClick={openImportModal}>
            批量导入
          </Button>
        </Space>
      </div>

      <div style={{ flex: 1, overflow: "hidden" }}>
        <div className="pds-table-container" style={{ height: "100%" }} ref={tableContainerRef}>
          <Table
            rowSelection={{ selectedRowKeys, columnWidth: 50, onChange: (keys) => setSelectedRowKeys(keys) }}
            columns={columns}
            dataSource={data}
            rowKey="id"
            loading={loading}
            pagination={{
              current,
              pageSize,
              total,
              showSizeChanger: true,
              pageSizeOptions: ["10", "20", "50"],
              onChange: (p, s) => { setCurrent(p); setPageSize(s!); },
              showTotal: (t) => `共 ${t} 条`,
            }}
            scroll={{ y: tableScrollY, x: "max-content" }}
            bordered
            size="small"
          />
        </div>
      </div>

      <Modal title={editing ? "编辑数据集" : "新建数据集"} open={modalOpen} onOk={handleSave} onCancel={() => setModalOpen(false)} width={600} okText="保存" cancelText="取消">
        <Form layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item label="数据集名称" required>
            <AntInput placeholder="请输入数据集名称" value={dataSetName} onChange={(e) => setDataSetName(e.target.value)} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="批量导入数据集"
        open={importOpen}
        onOk={handleImport}
        onCancel={() => setImportOpen(false)}
        okText="确认导入"
        cancelText="取消"
        confirmLoading={importLoading}
        width={600}
      >
        <Form layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item label="选择已有数据集名称（可多选）">
            <div style={{ maxHeight: 360, overflow: 'auto', padding: '8px 12px', border: '1px solid #f0f0f0', borderRadius: 4 }}>
              <Checkbox.Group
                options={allNames.map((n) => ({ label: n, value: n }))}
                value={selectedNames}
                onChange={(vals) => setSelectedNames(vals as string[])}
              />
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DataSetPanel;


